import React from 'react'
import PropTypes from 'prop-types'
import { Menu } from 'antd'
import { arrayToTree, queryArray } from 'utils'
import { classnames } from 'utils'
import router from 'umi/router'
// import pathToRegexp from 'path-to-regexp'
import styles from './ProdMenu.less'
const { SubMenu } = Menu
// const { Sider } = Layout
let openKeysFlag = false

const YQProdMenu = ({
  spreadProdMenu, prodNavOpenKeys, changeOpenKeys, prodMenu, location, prodMenubarTitle, switchProdMenu,
}) => {
  
  // 生成树状
  const menuTree = arrayToTree(prodMenu.filter(_ => _.mpid !== '-1'), 'id', 'mpid')
  const levelMap = {}
  // 递归生成菜单
  const getMenus = (menuTreeN, siderFoldN) => {
    return menuTreeN.map((item) => {
      if (item.children) {
        if (item.mpid) {
          levelMap[item.id] = item.mpid
        }
        return (
          <SubMenu
            key={item.id}
            title={<span>
            {(!siderFoldN || !menuTree.includes(item)) && item.name}
            </span>}
          >
            {getMenus(item.children, siderFoldN)}
          </SubMenu>
        )
      }
      return (
        <Menu.Item key={item.id}>
          {/* <Link to={item.link_to || '#'} style={siderFoldN ? { width: 10 } : {}}>{item.name}</Link> */}
          <div onClick={() => {handleProdMenu(item)}}>{item.name}</div>
        </Menu.Item>
      )
    })
  }
  const menuItems = getMenus(menuTree, !spreadProdMenu)

  // 菜单点击
  const handleProdMenu = (item) => {
    switch (item.link_type) {

      case "1":    // 内链跳转(无参数)
        router.push(`${item.link_to}`)
        break

      case "2":    // 外链跳转(无参数)
        window.location.href=`${item.link_to}`
        break

      default:
        break
    }
  }

  // 保持选中
  const getAncestorKeys = (key) => {
    let map = {}
    const getParent = (index) => {
      const result = [String(levelMap[index])]
      if (levelMap[result[0]]) {
        result.unshift(getParent(result[0])[0])
      }
      return result
    }
    for (let index in levelMap) {
      if ({}.hasOwnProperty.call(levelMap, index)) {
        map[index] = getParent(index)
      }
    }
    return map[key] || []
  }

  const onOpenChange = (openKeys) => {
    if (prodNavOpenKeys.length) changeOpenKeys([]), openKeysFlag = true
    const latestOpenKey = openKeys.find(key => !prodNavOpenKeys.includes(key))
    const latestCloseKey = prodNavOpenKeys.find(key => !openKeys.includes(key))
    let nextOpenKeys = []
    if (latestOpenKey) {
      nextOpenKeys = getAncestorKeys(latestOpenKey).concat(latestOpenKey)
    }
    if (latestCloseKey) {
      nextOpenKeys = getAncestorKeys(latestCloseKey)
    }
    changeOpenKeys(nextOpenKeys)
  }

  let menuProps = spreadProdMenu ? {
    onOpenChange,
    openKeys: prodNavOpenKeys,
  } : {}


  // 寻找选中路由
  let currentMenu
  let defaultSelectedKeys
  for (let item of prodMenu) {
    if (item.link_to && (location.pathname).includes(item['link_to'])) {
      if (!prodNavOpenKeys.length && item.mpid && !openKeysFlag) changeOpenKeys([String(item.mpid)])
      currentMenu = item
    } 
  }
  const getPathArray = (array, current, pid, id) => {
    let result = [String(current[id])]
    const getPath = (item) => {
      if (item && item[pid]) {
        if (item[pid] === '-1') {
          result.unshift(String(item['bpid']))
        } else {
          result.unshift(String(item[pid]))
          getPath(queryArray(array, item[pid], id))
        }
      }
    }
    return result
  }
  if (currentMenu) {
    defaultSelectedKeys = getPathArray(prodMenu, currentMenu, 'mpid', 'id')
  }
  
  return (
    <div className={styles.promenubar}>
      <div className={styles.toptitle}>{ prodMenubarTitle }</div>
      <Menu
        {...menuProps}
        mode='inline'
        selectedKeys={defaultSelectedKeys}
      >
        {menuItems}
      </Menu>
      <div className={classnames(styles.spreadProdMenu, {[styles.siderFold]: spreadProdMenu, [styles.siderNone]: !spreadProdMenu })} onClick={switchProdMenu}></div>
    </div>
  )
}

YQProdMenu.propTypes = {
  switchProdMenu: PropTypes.func,
  prodMenu: PropTypes.array,
  prodMenubarTitle:PropTypes.string,
  spreadProdMenu: PropTypes.bool,
  prodNavOpenKeys: PropTypes.array,
  changeOpenKeys: PropTypes.func,
  location: PropTypes.object,
}

export default YQProdMenu
